package com.office.shop.by;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import com.office.shop.by.components.*;
import org.json.JSONException;
import org.json.JSONObject;

import static android.graphics.BitmapFactory.decodeResource;

public class OfficeActivity extends Activity
{

    public static SharedPreferences sharedPreferences;
    public static OfficeActivity obj;

    private ProgressDialog pd;
    private Bundle savedInstanceState;


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        this.savedInstanceState =  savedInstanceState;
        obj = this;
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        sharedPreferences = MultiAccActivity.sharedPreferences;
        setContentView(R.layout.loading);
        Refresh();
    }

    public void Refresh()
    {
      pd = ProgressDialog.show(this, "", getString(R.string.DataUpdate), true, false);
      new JSONParser().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
           MenuInflater inflater = getMenuInflater();
           inflater.inflate(R.menu.main_menu, menu);
           return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //case R.id.mmSettings:
            //this.startActivitySettings();
            //return true;
            case R.id.mmRefresh:
            this.Refresh();
            return true;
            case R.id.mmBalancelog:
            this.startActivityBalanceLog();
            return true;
            case R.id.mmExit:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public void startActivitySettings()
    {
         Intent i = new Intent();
         i.setClass(this, SettingsActivity.class);
         i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(i);
    }

    public void startActivityBalanceLog()
    {
         Intent i = new Intent();
         i.setClass(this, BalanceLogActivity.class);
         i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(i);
    }

    public class JSONParser extends AsyncTask<String, Void, JSONObject>
    {
        protected JSONObject doInBackground(String arg[]) {
          JSONObject output = new JSONObject();
          try
          {
            if(CAuth.login(CAccounts.logins[MultiAccActivity.current_acc],
                         CAccounts.passwords[MultiAccActivity.current_acc]))
               output = CHttp.postJSON(CConfig.serverUrl, CAuth.getLogin());
            else
               output = null;
          }
          catch(Exception e)
          {
            e.printStackTrace();
          }
          return output;
        }


        //Событие по окончанию парсинга
        protected void onPostExecute(JSONObject output) {

            //ib.setImageResource(R.drawable.off);
            try {
                if(output != null)
                {
                    setContentView(R.layout.main);
                    TextView txtSumBalance = (TextView) findViewById(R.id.txtSumBalance);
                    TextView txtSumDbBalance = (TextView) findViewById(R.id.txtSumDbBalance);
                    TextView txtSumAdvBalance = (TextView) findViewById(R.id.txtSumAdvBalance);
                    TextView tvShopName = (TextView) findViewById(R.id.tvShopName);

                    TextView tvTpName = (TextView) findViewById(R.id.tvTpName);
                    TextView tvStatusB = (TextView) findViewById(R.id.tvStatusB);
                    TextView tvStatusDB = (TextView) findViewById(R.id.tvStatusDB);
                    TextView tvStatusAdvance = (TextView) findViewById(R.id.tvStatusAdvance);

                    ImageButton ibShopIcon = (ImageButton) findViewById(R.id.ibShopIcon);
                    ImageButton ibBalance = (ImageButton) findViewById(R.id.ibBalance);
                    ImageButton ibBalanceDB = (ImageButton) findViewById(R.id.ibBalanceDB);
                    ImageButton ibBalanceAdvance = (ImageButton) findViewById(R.id.ibBalanceAdvance);


                    tvTpName.setText(getString(R.string.TpTitle) + "«" + output.getJSONObject("tp").getString("name")+"»");
                    tvShopName.setText(output.getString("real_url"));


                    if(output.getJSONObject("host").getString("status").equals("active"))
                    {
                         ibBalance.setImageResource(R.drawable.on);
                         tvStatusB.setText(getString(R.string.ServiceActive));
                    }
                    else
                    {
                         ibBalance.setImageResource(R.drawable.off);
                         tvStatusB.setText(getString(R.string.ServiceNoActive));
                    }
                    txtSumBalance.setText(CFormat.numberFormat(output.getJSONObject("host").getString("purse_sum")));

                    if(output.getJSONObject("db").getString("status").equals("active"))
                    {
                       ibBalanceDB.setImageResource(R.drawable.on);
                       tvStatusDB.setText(getString(R.string.ServiceActive));
                    }
                    else
                    {
                          ibBalanceDB.setImageResource(R.drawable.off);
                          tvStatusDB.setText(getString(R.string.ServiceNoActive));
                    }
                    txtSumDbBalance.setText(CFormat.numberFormat(output.getJSONObject("db").getString("purse_sum")));

                    if(output.getJSONObject("advance").getString("status").equals("active"))
                    {
                             ibBalanceDB.setImageResource(R.drawable.on);
                             tvStatusDB.setText(getString(R.string.ServiceActive));
                    }
                    else
                    {
                             ibBalanceDB.setImageResource(R.drawable.off);
                             tvStatusDB.setText(getString(R.string.ServiceNoActive));
                    }
                    txtSumAdvBalance.setText(CFormat.numberFormat(output.getJSONObject("advance").getString("purse_sum")));

                    Bitmap img = CImages.fetchImage(output.getString("img_url"));
                    if(img != null)
                       ibShopIcon.setImageBitmap(img);
                    else
                        ibShopIcon.setImageBitmap(decodeResource(getResources(), R.drawable.icon));
                }
                else
                {
                    setContentView(R.layout.login);
                }
            } catch (JSONException e) {
                     pd.dismiss();
                     e.printStackTrace();

            }
             pd.dismiss();
        }
      }
}
